package com.anntly.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @Auther: 张文
 * @Date: 2020/5/1 11:22
 * @Description:
 */
public class BioServer {
    private static final int PORT = 6666;

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 200,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10),
                new ThreadPoolExecutor.AbortPolicy());
        while (true){
            // 获取socket连接
            Socket socket = serverSocket.accept();
            System.out.println("连接成功");
            pool.execute(()->{
                handleMsg(socket);
            });
        }
    }

    public static void handleMsg(Socket socket) {
        byte[] bytes = new byte[1024];
        int index = 0;
        try (
                InputStream inputStream = socket.getInputStream();
        ){
            while ((index = inputStream.read(bytes))!= -1){
                System.out.println(new String(bytes,0,index));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
